package com.icinfo.cloud.provider.common.zzd;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.xxpt.gateway.shared.client.http.ExecutableClient;
import com.alibaba.xxpt.gateway.shared.client.http.PostClient;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request.BtnJsonList;
import com.icinfo.cloud.provider.common.enums.MsgTypeEnum;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.punish.app.mapper.AppDingdingMessageMapper;
import com.icinfo.cloud.provider.punish.app.model.AppDingdingMessage;
import com.icinfo.framework.tools.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 浙证钉消息发送
 *
 * @author lxj
 * @data 2022/4/1
 */
@Slf4j
@Component
public class DingDingUtil {


    private static String worknotificationapi = "/message/workNotification";


    private static DingDingUtil dingDingUtil;
    @Resource
    AppDingdingMessageMapper appDingdingMessageMapper;
    @Value("${taizhouH5Url}")
    private  String taizhouH5Url;


    @PostConstruct
    public void init() {
        dingDingUtil = this;
        dingDingUtil.appDingdingMessageMapper = this.appDingdingMessageMapper;
        dingDingUtil.taizhouH5Url = this.taizhouH5Url;
    }
    /**
     * 发送工作消息通知
     */
    public static String sendWorkNotification(DingMsg dingMsg) {
        try {
            ExecutableClient executableClient = getExecutableClient();
            PostClient postClient = executableClient.newPostClient(worknotificationapi);
            DingDingDto dingDingDto = dingMsg.getDingDingDto();

            JSONObject obj = new JSONObject();
            //卡片消息
            obj.put("title", dingDingDto.getTitle());
            obj.put("markdown", dingDingDto.getDingMsg());
            obj.put("btn_orientation", "1");
            if (CollectionUtils.isNotEmpty(dingDingDto.getBtnJsonListList())) {
                List<BtnJsonList> btnJsonList = dingDingDto.getBtnJsonListList();
                List<Object> btnJsonList2 = Lists.newArrayList();
                for (BtnJsonList jsonList : btnJsonList) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("title", jsonList.getTitle());
                    jsonObject.put("action_pc_url", jsonList.getActionUrl());
                    jsonObject.put("action_mobile_url", jsonList.getActionUrl());
                    btnJsonList2.add(jsonObject);
                }
                obj.put("btn_json_list", btnJsonList2);
            }

            String msgType = "action_card";
            JSONObject msgObj = new JSONObject();
            msgObj.put("msgtype", msgType);
            msgObj.put(msgType, obj);

            //设置参数
            postClient.addParameter("organizationCodes", "");
            postClient.addParameter("receiverIds", dingMsg.getReceiverUserids());
            postClient.addParameter("tenantId", "196729");
            postClient.addParameter("bizMsgId", "");
            postClient.addParameter("msg", msgObj.toJSONString());
            //调用API
            String apiResult = postClient.post();
            executableClient.destroy();
            JSONObject jsonObject = JSONObject.parseObject(apiResult);
            System.out.println(apiResult);
            //{"success":true,"content":{"msgId":"6245b22fae044b228f64f725cbd1dfb6"}}
            if (jsonObject != null && jsonObject.getBoolean("success") == true) {
                return jsonObject.getJSONObject("content").getString("msgId");
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }


    public static ExecutableClient getExecutableClient() {
        ExecutableClient executableClient = ExecutableClient.getInstance();
        executableClient.setAccessKey("hlwjg_zszf-U0PRscL0Oh0XXyIRbE3");
        executableClient.setSecretKey("0eR4FJGY5T39E7ww533A6NOPg998o34ur05NP4Up");
        executableClient.setDomainName("10.145.147.112:8581/proxy/dingAddr");
        executableClient.setProtocal("http");
        executableClient.init();
        return executableClient;
    }

    /**
     * 创建请求发送
     *
     * @param dingId   发送的钉id
     * @param title    发送标题
     * @param msg      发送正文
     * @param btnTitle
     * @param url      跳转地址
     * @return
     */
    public static DingMsg createDing(String dingId, String title, String msg, String btnTitle, String url) {
        DingMsg dingMsg = new DingMsg();
        dingMsg.setSendUserid("");
        dingMsg.setReceiverUserids(dingId);
        DingDingDto dto = new DingDingDto();
        dto.setTitle(title);
        dto.setDingMsg(msg);
        dto.setDingMsgType("action_card");

        List<BtnJsonList> btnJsonListList = new ArrayList<>();
        BtnJsonList btn = new BtnJsonList();
        btn.setTitle(btnTitle);
        btn.setActionUrl(url);
        btnJsonListList.add(btn);
        dto.setBtnJsonListList(btnJsonListList);
        dingMsg.setDingDingDto(dto);
        return dingMsg;
    }

    public static String getAccountIdByMobile(String mobile) {
        ExecutableClient executableClient = getExecutableClient();
        PostClient postClient = executableClient.newPostClient("/mozi/employee/get_by_mobile");
        //设置参数
        postClient.addParameter("areaCode", "86");
        postClient.addParameter("tenantId", "196729");
        postClient.addParameter("namespace", "local");
        postClient.addParameter("mobile", mobile);
        //调用API
        String apiResult = postClient.post();
        System.out.println(apiResult);

        if (StringUtils.isBlank(apiResult)) {
            executableClient.destroy();
            return null;
        }
        JSONObject resultObj = JSONObject.parseObject(apiResult);
        Object content = resultObj.get("content");
        JSONObject contentObj = JSONObject.parseObject(content.toString());
        boolean success = (boolean) contentObj.get("success");
        executableClient.destroy();
        if (success) {
            JSONObject data = JSONObject.parseObject(contentObj.get("data").toString());
            return data.get("accountId").toString();
        }
        return null;
    }

    /**
     *  创建浙证钉打开的链接url
     * @param dingId        接收人的dingId
     * @param caseId        案件id
     * @param documentCatalogCode  文书目录编码
     * @param taskStatus     0.待审批，1.已审批
     * @param waitStatus    0.剩余，1.已到期，2.超时了
     * @return String
     */
     public static String createUrl(String dingId ,String caseId ,String documentCatalogCode,String taskStatus,String waitStatus){
         String a = "{\"id\":\""+caseId+"\",\"documentCatalogCode\":\""+documentCatalogCode+"\",\"taskStatus\":"+taskStatus+",\"waitStatus\":"+waitStatus+"}" ;

         String url = dingDingUtil.taizhouH5Url+"/zsba-h5/transition-page?accountId="+dingId+"&path=/my-approve/audit-detail&query="+ URLEncoder.encode(a);
         System.out.println(url);
         return url;
     }
    /**
     *  创建浙证钉打开的链接url
     * @param dingId        接收人的dingId
     * @param caseId        案件id
     * @param documentCatalogCode  文书目录编码
     * @param taskStatus     0.待审批，1.已审批
     * @param waitStatus    0.剩余，1.已到期，2.超时了
     * @return String
     */
    public static String createExecuteUrl(String dingId ,String caseId ,String documentCatalogCode,String taskStatus,String waitStatus){
        String a = "{\"id\":\""+caseId+"\",\"documentCatalogCode\":\""+documentCatalogCode+"\",\"taskStatus\":"+taskStatus+",\"waitStatus\":"+waitStatus+"}" ;

        String url = dingDingUtil.taizhouH5Url+"/zsba-h5/transition-page?accountId="+dingId+"&path=/my-approve/audit-detail&query="+ URLEncoder.encode(a);
        System.out.println(url);
        return url;
    }
    /**
     * 模板1-
     * 审批-审批人----新的审批任务提示
     *
     * @param orgName      办案机构名称
     * @param name         接收人姓名
     * @param documentName 文书名称
     * @param dingId       审批人dingId
     * @param timeLimit    时效
     * @param url          链接
     * @return boolean
     */
    public static boolean newAuditMsg(String caseId,String documentCatalogCode,String orgName,String name, String documentName, String dingId, String timeLimit, String url) {
        String title = "新的审批任务提示";
        String msg = "您有一份来自于" + orgName + "的【" + documentName + "】待审批，审批时效" + timeLimit + "，请前往审批任务列表查看(消息时间:"+DateUtils.getDate("yyyy-MM-dd HH:mm:ss")+")";
        if(StringUtils.isEmpty(url)){
            url = createUrl(dingId,caseId,documentCatalogCode,"0","0");
        }
        DingMsg dingMsg = createDing( dingId, title, msg, "去审核", url);

        String msgId =  sendWorkNotification(dingMsg);
        if(StringUtils.isEmpty(msgId)){
            return false;
        }
        return saveAppDingMsg(caseId,title,msg,msgId,dingId,name,url, MsgTypeEnum.xsp.getMsg());
    }
    /**
     * 模板1-
     * 审批-审批人----新的审批任务提示
     *
     * @param orgName      办案机构名称
     * @param name         接收人姓名
     * @param documentName 文书名称
     * @param dingId       审批人dingId
     * @param timeLimit    时效
     * @param url          链接
     * @return boolean
     */
    public static boolean newExecuteAuditMsg(String caseId,String documentCatalogCode,String orgName,String name, String documentName, String dingId, String timeLimit, String url) {
        String title = "新的审批任务提示";
        String msg = "您有一份来自于" + orgName + "的【" + documentName + "】待审批，审批时效" + timeLimit + "，请前往审批任务列表查看(消息时间:"+DateUtils.getDate("yyyy-MM-dd HH:mm:ss")+")";
        if(StringUtils.isEmpty(url)){
            url = createExecuteUrl(dingId,caseId,documentCatalogCode,"0","0");
        }
        DingMsg dingMsg = createDing( dingId, title, msg, "去审核", url);

        String msgId =  sendWorkNotification(dingMsg);
        if(StringUtils.isEmpty(msgId)){
            return false;
        }
        return saveAppDingMsg(caseId,title,msg,msgId,dingId,name,url, MsgTypeEnum.xsp.getMsg());
    }

    /**
     * 模板2-
     * 审批-审批人----审批通过
     *
     * @param url          链接
     * @param documentName 文书名称
     * @param dingId       审批人dingId
     * @param name         接收人姓名
     * @return boolean
     */
    public static boolean auditPassMsg(String caseId,String documentCatalogCode,String documentName, String dingId, String name, String url) {
        String title = "审批通过提示";
        String msg = "您的【" + documentName + "】审批完成，点击查看审批详情。(消息时间:"+DateUtils.getDate("yyyy-MM-dd HH:mm:ss")+")";
        if(StringUtils.isEmpty(url)){
            url = createUrl(dingId,caseId,documentCatalogCode,"0","0");
        }
        DingMsg dingMsg = createDing( dingId, title, msg, "去查看", url);
        String msgId =  sendWorkNotification(dingMsg);
        if(StringUtils.isEmpty(msgId)){
            return false;
        }
        return saveAppDingMsg(caseId,title,msg,msgId,dingId,name,url, MsgTypeEnum.sptg.getMsg());
    }

    /**
     * 模板3-
     * 审批-发起人----被审批通过
     *
     * @param url          链接
     * @param documentName 文书名称
     * @param dingId       审批人dingId
     * @return boolean
     */
    public static boolean auditedMsg(String caseId,String documentCatalogCode,String documentName,String name, String dingId, String url) {
        String title = "审批通过提示";
        String msg = "您的【" + documentName + "】审批完成，点击查看审批详情。(消息时间:"+DateUtils.getDate("yyyy-MM-dd HH:mm:ss")+")";
        if(StringUtils.isEmpty(url)){
            url = createUrl(dingId,caseId,documentCatalogCode,"1","0");
        }
        DingMsg dingMsg = createDing(dingId, title, msg, "去查看", url);
        String msgId =  sendWorkNotification(dingMsg);
        if(StringUtils.isEmpty(msgId)){
            return false;
        }
        return saveAppDingMsg(caseId,title,msg,msgId,dingId,name,url, MsgTypeEnum.fqtg.getMsg());
    }

    /**
     * 模板4-
     * 审批-发起人----被审批退回
     *
     * @param url          链接
     * @param documentName 文书名称
     * @param dingId       审批人dingId
     * @return boolean
     */
    public static boolean auditRetiredMsg(String caseId,String documentCatalogCode,String documentName, String dingId,String name,  String url) {
        String title = "审批退回提示";
        String msg = "您的【" + documentName + "】审批退回，点击查看审批详情。(消息时间:"+DateUtils.getDate("yyyy-MM-dd HH:mm:ss")+")";
        if(StringUtils.isEmpty(url)){
            url = createUrl(dingId,caseId,documentCatalogCode,"1","0");
        }
        DingMsg dingMsg = createDing( dingId, title, msg, "去查看", url);
        String msgId =  sendWorkNotification(dingMsg);
        if(StringUtils.isEmpty(msgId)){
            return false;
        }
        return saveAppDingMsg(caseId,title,msg,msgId,dingId,name,url, MsgTypeEnum.spth.getMsg());
    }

    /**
     * 模板5-
     * 办案人----案件到期提示
     *
     * @param url        链接
     * @param caseNumber 案件编号
     * @param dingId     审批人dingId
     * @param partyName   当事人
     * @param caseReason  案由
     * @return boolean
     */
    public static boolean expireMsg(String caseId,String documentCatalogCode,String caseNumber, String expireTime, String dingId,String name, String partyName, String caseReason, String url) {
        String title = "案件到期提示";
        String msg = "您编号【" + caseNumber + "】的案件将在" + expireTime + "后过期，请尽快处理。\n\n"
                +"当事人："+partyName+"\n\n"
                +"案由："+caseReason;
        if(StringUtils.isEmpty(url)){
            url = createUrl(dingId,caseId,documentCatalogCode,"0","0");
        }
        DingMsg dingMsg = createDing( dingId, title, msg, "去查看", url);
        String msgId =  sendWorkNotification(dingMsg);
        if(StringUtils.isEmpty(msgId)){
            return false;
        }
        return saveAppDingMsg(caseId,title,msg,msgId,dingId,name,url, MsgTypeEnum.ajdq.getMsg());
    }
    /**
     * 模板6-
     * 办案人----案件自动执行完毕
     *
     * @param url        链接
     * @param caseNumber 案件编号
     * @param dingId     审批人dingId
     * @param punishType   处罚种类
     * @param money       交款金额
     * @return boolean
     */
    public static boolean autoAuditMsg(String caseId,String documentCatalogCode,String caseNumber, String punishType, String dingId ,String name, String money, String url) {
        String title = "案件自动执行完毕";
        String msg = "您编号【" + caseNumber + "】的案件自动执行完成。"
                +"\n\n处罚种类："+punishType
                +"\n\n缴费金额：人民币 "+money +"元整";
        if(StringUtils.isEmpty(url)){
            url = createUrl(dingId,caseId,documentCatalogCode,"0","0");
        }
        DingMsg dingMsg = createDing( dingId, title, msg, "去查看", url);
        String msgId =  sendWorkNotification(dingMsg);
        if(StringUtils.isEmpty(msgId)){
            return false;
        }
        return saveAppDingMsg(caseId,title,msg,msgId,dingId,name,url, MsgTypeEnum.ajzdzx.getMsg());
    }

    /**
     * 模板7-
     * 办案人----文书送达临期提示
     *
     * @param url        链接
     * @param caseNumber 案件编号
     * @param dingId     审批人dingId
     * @param partyName   当事人
     * @param wsType       文书类型
     * @return boolean
     */
    public static boolean wsMomentMsg(String caseId,String documentCatalogCode, String caseNumber, String partyName, String dingId,String name, String wsType, String url) {
        String title = "文书送达临期提示";
        String msg = "您编号【" + caseNumber + "】的文书即将送达超期。"
                +"\n\n当事人："+partyName
                +"\n\n文书类型："+wsType ;
        if(StringUtils.isEmpty(url)){
            url = createUrl(dingId,caseId,documentCatalogCode,"0","0");
        }
        DingMsg dingMsg = createDing( dingId, title, msg, "去处理", url);
        String msgId =  sendWorkNotification(dingMsg);
        if(StringUtils.isEmpty(msgId)){
            return false;
        }
        return saveAppDingMsg(caseId,title,msg,msgId,dingId,name,url, MsgTypeEnum.wslq.getMsg());
    }

    /**
     * 模板8-
     * 办案人----案件缴费完成提示
     * @param url        链接
     * @param caseNumber 案件编号
     * @param dingId     审批人dingId
     * @param payType     缴费种类
     * @param money       缴费金额
     * @return boolean
     */
    public static boolean payFinishMsg(String caseId,String documentCatalogCode,String caseNumber, String payType, String dingId,String name, String money, String url) {
        String title = "案件缴费完成提示";
        String msg = "您编号【" + caseNumber + "】的案件缴费已完成。"
                +"\n\n缴费种类："+payType
                +"\n\n缴费金额：人民币"+money+"元" ;
        if(StringUtils.isEmpty(url)){
            url = createUrl(dingId,caseId,documentCatalogCode,"0","0");
        }
        DingMsg dingMsg = createDing( dingId, title, msg, "去查看", url);
        String msgId =  sendWorkNotification(dingMsg);
        if(StringUtils.isEmpty(msgId)){
            return false;
        }
        return saveAppDingMsg(caseId,title,msg,msgId,dingId,name,url, MsgTypeEnum.ajjf.getMsg());
    }

    /**
     * 添加发送记录
     * @param caseId    案件id
     * @param title
     * @param content
     * @param msgId
     * @param dingId
     * @param realName
     * @param url
     */
    public static boolean saveAppDingMsg(String caseId,String title,String content,String msgId,String dingId,String realName,String url,String msgType){

        AppDingdingMessage appDingdingMessage = new AppDingdingMessage();
        appDingdingMessage.setTitle(title);
        appDingdingMessage.setMessageType(msgType);
        appDingdingMessage.setContent(content);
        appDingdingMessage.setMessageId(msgId);
        appDingdingMessage.setReadStatus("0");
        appDingdingMessage.setCreateTime(new Date());
        appDingdingMessage.setReceiverUserDingId(dingId);
        appDingdingMessage.setReceiverUserName(realName);
        appDingdingMessage.setLinkUrl(url);
        appDingdingMessage.setId(BaseUtil.createUid());
        appDingdingMessage.setCaseId(caseId);
        int flag = dingDingUtil.appDingdingMessageMapper.insert(appDingdingMessage);
        if(flag>0){
            return true;
        }
        return false;
    }

}
